package org.bim.view.drag.design.interceptor;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bim.view.drag.design.api.vo.TUserVO;
import org.bim.view.drag.design.config.DesignerLoginService;
import org.bim.view.drag.design.exception.BizCommonException;
import org.bim.view.drag.design.util.ThreadLocalUtil;
import org.bim.view.drag.design.util.TokenUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Slf4j
@AllArgsConstructor
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        String token = TokenUtil.getUserToken();
        if(StringUtils.isEmpty(token)){
            throw new BizCommonException("未授权",401);
        }
        TUserVO currentUser =DesignerLoginService.onlineUserMap.get(token);
        if(currentUser==null){
            throw new BizCommonException("未授权",401);
        }
        ThreadLocalUtil.setCurrentUser(currentUser);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        log.info("拦截器postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                Exception ex) throws Exception {
        log.info("拦截器afterCompletion");
    }

}
